import React, { Component } from 'react'
import { Row, Col, Form, Input, Modal, Button, Table, Alert } from 'antd'
import { connect } from 'dva'
import columns from '../propList/columns'
import styles from './Index.less'
import settings from '@/../config/defaultSettings'

const FormItem = Form.Item

@connect(({ loading, property }) => ({
  property,
  loading: loading.models.property,
}))
@Form.create()
export default class PropModal extends Component {
  state = {
    // selectRecords: this.props.selectRecords ? this.props.selectRecords : {},
    // selectedRowKeys: this.props.selectedRowKeys ? this.props.selectedRowKeys : [],
    selectRecords: {},
    selectedRowKeys: [],
  }

  componentDidMount() {
    const { dispatch } = this.props
    dispatch({
      type: 'property/fetchList',
      payload: {
        size: 5,
      },
    })
  }

  //
  componentDidUpdate(prevProps) {
    // this.prevProps.storeState.currentItem. items? 初始化 this.state.selectedRowKeys
    if (!prevProps.showModal && this.props.showModal) {
      const { currentItem } = this.props.storeState
      const selectRecords = {}
      // eslint-disable-next-line react/no-did-update-set-state
      this.setState({
        selectedRowKeys: currentItem.items
          ? currentItem.items.map(item => {
              selectRecords[item.id] = item
              return item.id
            })
          : [],
        selectRecords,
      })
    }
  }

  // 关闭窗口
  handleClose = () => {
    // 重置窗口内数据
    const { resetFields } = this.props.form
    resetFields()
    this.props.dispatch({
      type: 'property/fetchList',
      payload: {
        size: 5,
      },
    })
    this.props.modalCloseCallback()
  }

  // 弹窗确认
  handleConfirm = () => {
    const { selectRecords } = this.state
    this.props.modalConfirmCallback(Object.keys(selectRecords).map(key => selectRecords[key]))
  }

  // 重置事件
  handleFormReset = () => {
    const { form, dispatch } = this.props
    form.resetFields()

    dispatch({
      type: 'property/fetchList',
      payload: {
        size: 5,
      },
    })
  }

  handleSearch = e => {
    e.preventDefault()
    //
    const { form, dispatch } = this.props
    // 表单验证
    form.validateFields((err, fieldsValue) => {
      if (err) return

      const values = {
        ...fieldsValue,
        size: 5,
      }

      dispatch({
        type: 'property/fetchList',
        payload: values,
      })
    })
  }

  // 表格动作触发事件
  handleListChange = (pg, filtersArg, sorter) => {
    const { dispatch } = this.props
    const { formValues, pagination } = this.props.property
    if (sorter.field && pagination.currentPage === pg.current) {
      return
    }

    const params = {
      // size: pg.pageSize,
      ...formValues,
      current: pg.current,
      size: 5,
      // ...filters,
    }

    dispatch({
      type: 'property/fetchList',
      payload: params,
    })
  }

  // 行选事件
  handleSelectRows = (rowkeys, selectRows) => {
    const { selectRecords } = this.state
    const handleRecords = {}
    rowkeys.forEach(key => {
      if (selectRecords[key]) {
        handleRecords[key] = selectRecords[key]
      } else {
        handleRecords[key] = selectRows.find(row => row.id === key)
      }
    })

    this.setState({
      selectRecords: handleRecords,
      selectedRowKeys: rowkeys,
    })
  }

  // 渲染界面
  render() {
    const { loading, showModal } = this.props
    const { getFieldDecorator } = this.props.form
    const { list, pagination } = this.props.property
    const { selectedRowKeys } = this.state
    const rowSelectionProps = {
      selectedRowKeys,
      onChange: (selectedKeys, selectedRows) => {
        this.handleSelectRows(selectedKeys, selectedRows)
      },
    }
    // const formItemLayout = {
    //   labelCol: { span: 8 },
    //   wrapperCol: { span: 14 },
    // }
    const formRowOne = {
      labelCol: { span: 6 },
      wrapperCol: { span: 18 },
    }
    return (
      <Modal
        maskClosable={false}
        confirmLoading={loading}
        cancelText="取消"
        okText="确认"
        onCancel={() => this.handleClose()}
        visible={showModal}
        width={1000}
        onOk={() => this.handleConfirm()}
        title="选择资产"
      >
        <Form className={styles.modalForm} onSubmit={this.handleSearch}>
          <Row gutter={{ md: 8, lg: 24, xl: 48 }}>
            <Col md={12} sm={24}>
              <FormItem label="*资产编码" {...formRowOne}>
                {getFieldDecorator('zcCode')(
                  <Input placeholder="请输入" maxLength={settings.inputMaxLength} />,
                )}
              </FormItem>
            </Col>
            <Col md={12} sm={24}>
              <FormItem label="*资产名称" {...formRowOne}>
                {getFieldDecorator('zcName')(
                  <Input placeholder="请输入" maxLength={settings.inputMaxLength} />,
                )}
              </FormItem>
            </Col>
          </Row>
          <div style={{ display: 'flex', marginBottom: 10 }}>
            <Button
              style={{ marginLeft: 'auto' }}
              type="primary"
              htmlType="submit"
              loading={loading}
            >
              查询
            </Button>
            <Button style={{ marginLeft: 8 }} onClick={this.handleFormReset} loading={loading}>
              重置
            </Button>
          </div>
        </Form>
        <Alert
          style={{ marginBottom: 8 }}
          message={
            <div>
              已选择 <a style={{ fontWeight: 600 }}>{selectedRowKeys.length}</a> 项&nbsp;&nbsp;
              <a style={{ marginLeft: 24 }} onClick={() => this.handleSelectRows([])}>
                清空选择
              </a>
            </div>
          }
          type="info"
          showIcon
        />
        <Table
          loading={loading}
          size="small"
          bordered
          dataSource={list}
          // rowKey={record => record.id}
          rowKey="id"
          pagination={pagination}
          columns={columns}
          onChange={this.handleListChange}
          rowSelection={rowSelectionProps}
        />
      </Modal>
    )
  }
}
